home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: Memory allocation.
- Date: 10 Feb 1996 20:48:54 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Feb10214855@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: Kajdan Dimitry's message of Sat, 10 Feb 1996 16:15:30 GMT
-
- In article <1996Feb10.161530.26449@wisipc.weizmann.ac.il> Kajdan Dimitry <cerlpvk> writes:
-
- I'm a starter so the question may seem stupid.
-
- Would someone explain why this program works?
-
- int* func()
- {
-
-
- int b[10];
- for(int i=0;i<9;i++)
- b[i]=i;
- return b;
- }
-
- int main(){
-
- int* x= func();
-
-
- cout<<x[2]<<endl;
- return(1);
- }
-
- The point is that b is allocated on the stack i.e without "new".
-
- Thanks in advance.
-
- This program _may_ works. In your example the elements of the array
- are obviously still accessible, although they are not part of the
- actual stack-frame of the main procedure. It's very likely that the
- slightly modified program
-
- >>>>
- #include <iostream.h>
-
- int* func(int off)
- {
- int b[10];
- for(int i=0;i<9;i++)
- b[i]=i+off;
- return b;
- }
-
- int main()
- {
- int* x= func(0);
- func(1);
-
- cout<<x[2]<<endl;
- return(1);
- }
- <<<<
-
- produces a different result, because the same memory gets modified in the
- 2nd call of 'func'. However the correct explaination completely depends on
- your environment. And of course - in general you cannot rely on this behavior.
-
- Enno
- --
- Enno
-